package com.hp.search_service.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hp.common_api.entity.*;
import com.hp.search_service.entity.Goods;
import com.hp.search_service.feign.GoodsFeignClient;
import com.hp.search_service.repository.GoodsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class GoodsIndexService {

    @Autowired
    private ElasticsearchTemplate template;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private GoodsFeignClient goodsFeignClient;

    /**
     * 建索引
     */
    public void createGoodsIndex(){
        template.deleteIndex(Goods.class);
        template.createIndex(Goods.class);
        template.putMapping(Goods.class);
    }

    /**
     * 导入商品数据
     */
    public void importGoodsData(){
        //调用商品服务的spu分页查询方法
        for(long i = 1; ;i++){
            PageResult<Spu> body = goodsFeignClient.getSpuPage(i).getBody();
            List<Spu> spus = body.getRecords();
            spus.forEach(spu -> {
                //将Spu--->Goods
                Goods goods = createGoodsFromSpu(spu);
                System.out.println(goods);
                //存入ES
                goodsRepository.save(goods);
            });
            //判断是否到了最后一页
            if(spus.size() < 10){
                break;
            }
        }
    }

    public Goods createGoodsFromSpu(Spu spu){
        //json解析对象
        ObjectMapper mapper = new ObjectMapper();
        //创建Goods商品
        Goods goods = new Goods();
        goods.setId(spu.getId());
        goods.setBrandId(spu.getBrandId());
        goods.setCid1(spu.getCid1());
        goods.setCid2(spu.getCid2());
        goods.setCid3(spu.getCid3());
        goods.setCreateTime(new Date());
        //获得分类的名称
        String name1 = goodsFeignClient.getCategoryNameById(spu.getCid1()).getBody();
        String name2 = goodsFeignClient.getCategoryNameById(spu.getCid2()).getBody();
        String name3 = goodsFeignClient.getCategoryNameById(spu.getCid3()).getBody();
        Brand brand = goodsFeignClient.getBrandById(spu.getBrandId()).getBody();
        String all = String.join(" ", spu.getTitle(), name1, name2, name3, brand.getName());
        goods.setAll(all);
        //查询sku
        List<Sku> skus = goodsFeignClient.getSkusBySpuId(spu.getId()).getBody();
        //添加价格集合
        List<Long> prices = new ArrayList<>();
        List<Map<String,Object>> skuList = new ArrayList<>();
        skus.forEach(sku -> {
            prices.add(sku.getPrice());
            Map<String,Object> map = new HashMap<>();
            map.put("id",sku.getId());
            map.put("title",sku.getTitle());
            map.put("price",sku.getPrice());
            map.put("image",sku.getImages().length() > 0 ? sku.getImages().split(",")[0] :"");
            skuList.add(map);
        });
        goods.setPrices(prices);
        //将sku转换json字符串
        try {
            goods.setSkus(mapper.writeValueAsString(skuList));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        goods.setSubTitle(spu.getSubTitle());
        //将spudetail查询出来
        SpuDetail detail = goodsFeignClient.getSpuDetailBySpuId(spu.getId()).getBody();
        //将通用规格和特殊规格解析为Map<String,Object>结构
        try {
            Map<String,Object> genericSpec = mapper.readValue(detail.getGenericSpec(),
                    new TypeReference<Map<String, Object>>() {});
            Map<String,Object> specialSpec = mapper.readValue(detail.getSpecialSpec(),
                    new TypeReference<Map<String, Object>>() {});
            //搜索的规格
            Map<String,String> specMap = new HashMap<>();
            //通过分类查询所有规格
            List<SpecParam> params = goodsFeignClient.getSpecParamsByCategoryId(spu.getCid3()).getBody();
            params.forEach(param -> {
                //是否可以搜索
                if(param.getSearching()){
                    //是否是通用的
                    if(param.getGeneric()){
                        //从通用的Map取得值，存到集合中
                        specMap.put(param.getName(),genericSpec.get(param.getId().toString()).toString());
                    }else{
                        specMap.put(param.getName(),specialSpec.get(param.getId().toString()).toString());
                    }
                }
            });
            goods.setSpecs(specMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return goods;
    }
}
